// 云函数入口文件
const cloud = require('wx-server-sdk');
const axios = require('axios');
const res = require('./res');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const ResponseDTO = require('./res');
const db = cloud.database();
const USER = 'edu-cloud-users'

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  // let openid = wxContext.OPENID;
  // 获取当前用户是否绑定教务系统
  let queryRes = await db.collection(USER).where({
    openid: wxContext.OPENID || event.openid
  }).get();
  if (queryRes.data.length == 0) {
    console.warn('未查询到该用户信息');
    return;
  }
  let userBase = queryRes.data[0];
  /**初始化请求接口 */
  var EDU_API = 'http://jwgl.sdust.edu.cn/app.do?method=authUser&xh=#{xh}&pwd=#{password}';
  /** 替换请求参数 */
  EDU_API = EDU_API.replace('#{xh}', userBase.bindId);
  EDU_API = EDU_API.replace('#{password}', userBase.bindPwd);
  /** 模拟请求 */
  let reqRes = await axios({
    method: "GET",
    url: EDU_API,
    headers: {
      "content-type": "application/json;charset=utf-8",
      "User-Agent": "Mozilla/5.0 (Linux; U; Mobile; Android 6.0.1;C107-9 Build/FRF91 )",
      "cache-control": "max-age=0"
    }
  })
  console.log(reqRes);
  let res = reqRes;
  if (res.status != 200) {
    return ResponseDTO.wrap(500, "SERVER ERROR");
  } else if (res.data.flag == '1' || res.data.flag == 1 || res.data.flag == true) {
    /** 更新TOKEN */
    db.collection(USER).doc(userBase._id).update({
      data: {
        token: res.data.token
      }
    }).then(cres => {
      console.log(cres)
    })
    return ResponseDTO.succData(res.data);
  } else {

    return ResponseDTO.wrap(500, res.data.msg);
  }
}